package Frontend

import (
	"fmt"
	"net/http"
	"strconv"
)

func Admin_up_profession(w http.ResponseWriter, r *http.Request)  {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	name:=r.PostFormValue("name")
	id,_:=strconv.Atoi(r.PostFormValue("id"))
	sqlStr := "update profession set name=? where id = ?;"
	ret, err := db.Exec(sqlStr, name,id)
	if err != nil {
		fmt.Printf("update failed, err:%v\n", err)
		return
	}
	n, err := ret.RowsAffected() // 操作影响的行数
	if err != nil {
		fmt.Printf("get RowsAffected failed, err:%v\n", err)
		return
	}
	fmt.Printf("update success, affected rows:%d\n", n)
	jsonk := `{"isok":"ok","msg":"修改成功"}`
	w.Write([]byte(jsonk)) //给客户端返回数据。
}

func Admin_set_profession(w http.ResponseWriter, r *http.Request)  {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	name:=r.PostFormValue("name")
	sqlStr := "insert into profession(name) values (?)"
	ret, err := db.Exec(sqlStr, name)
	if err != nil {
		fmt.Printf("insert failed, err:%v\n", err)
		return
	}
	theID, err := ret.LastInsertId() // 新插入数据的id
	if err != nil {
		fmt.Printf("get lastinsert ID failed, err:%v\n", err)
		return
	}
	fmt.Printf("insert success, the id is %d.\n", theID)
	jsonk := `{"isok":"ok","msg":"修改成功"}`
	w.Write([]byte(jsonk)) //给客户端返回数据。
}

func Admin_dele_profession(w http.ResponseWriter, r *http.Request)  {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	id,_:=strconv.Atoi(r.PostFormValue("id"))
	sqlStr := `DELETE profession,course,class,register_record FROM profession LEFT JOIN course ON profession.id=course.profession_id LEFT JOIN class ON course.id=class.course_id LEFT JOIN register_record ON register_record.class_id=class.id WHERE profession.id=?;`
	ret, err := db.Exec(sqlStr, id)
	if err != nil {
		fmt.Printf("delete failed, err:%v\n", err)
		return
	}
	n, err := ret.RowsAffected() // 操作影响的行数
	if err != nil {
		fmt.Printf("get RowsAffected failed, err:%v\n", err)
		return
	}
	fmt.Printf("delete success, affected rows:%d\n", n)
	jsonk := `{"isok":"ok","msg":"修改成功"}`
	w.Write([]byte(jsonk)) //给客户端返回数据。
}